import { useState, useRef } from "react";
import Tooltip from "./Tooltip";

export default function ButtonWithTooltip({
  tooltipContent,
  ...rest
}: {
  tooltipContent: React.ReactNode;
  children: React.ReactNode;
}) {
  // 补全 targetRect 类型定义
  type targetRect = {
    left: number;
    top: number;
    right: number;
    bottom: number;
  };
  const [targetRect, setTargetRect] = useState<targetRect | null>(null);
  const buttonRef = useRef<HTMLButtonElement>(null);
  return (
    <>
      <button
        {...rest}
        ref={buttonRef}
        onPointerEnter={() => {
          const rect =
            buttonRef.current && buttonRef.current.getBoundingClientRect();
          rect &&
            setTargetRect({
              left: rect.left,
              top: rect.top,
              right: rect.right,
              bottom: rect.bottom,
            });
        }}
        onPointerLeave={() => {
          setTargetRect(null);
        }}
      />
      {targetRect !== null && (
        <Tooltip targetRect={targetRect}>{tooltipContent}</Tooltip>
      )}
    </>
  );
}
